import { useEffect, useState } from 'react';
import { Card, Typography, Row, Col, Spin, Pagination, Layout } from 'antd';
import axios from 'axios';
import { Link } from 'react-router-dom';
import Sidebar from '../Sidebar.jsx';
import './index.css';

const { Meta } = Card;
const { Title, Text } = Typography;
const { Sider, Content } = Layout;

const ArticleList = () => {
    const [articles, setArticles] = useState([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [loading, setLoading] = useState(true);
    const articlesPerPage = 12;

    useEffect(() => {
        const fetchArticles = async () => {
            try {
                const response = await axios.get('/api/articles');
                console.log('Fetched articles:', response.data);
                const actualArticles = response.data || [];
                const processedArticles = actualArticles.map((article) => ({
                    ...article,
                    id: article.article_id, // 使用文章的唯一 id
                    image: 'default-image-url.jpg', // 提供默认图片 URL
                    content: article.original_text // 使用 original_text 作为内容
                }));
                setArticles(processedArticles);
            } catch (error) {
                console.error('Error fetching articles:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchArticles();
    }, []);

    const indexOfLastArticle = currentPage * articlesPerPage;
    const indexOfFirstArticle = indexOfLastArticle - articlesPerPage;
    const currentArticles = articles.slice(indexOfFirstArticle, indexOfLastArticle);

    const paginate = (pageNumber) => setCurrentPage(pageNumber);

    return (
        <Layout style={{ minHeight: '100vh' }}>
            <Sider width={200} style={{ background: '#f7f7f7',marginTop:'50px' }}>
                <Sidebar />
            </Sider>
            <Content style={{ margin: '24px 16px 0', overflow: 'initial' }}>
                <div className='article-list-container'>
                    <Title level={2} style={{ textAlign: 'center', color: '#211f3f' }}>
                        全部文章
                    </Title>
                    {loading ? (
                        <Spin size="large" style={{ margin: '0 auto', display: 'block' }} />
                    ) : (
                        <>
                            <Row gutter={[16, 16]} justify="center" className="row-of-cards">
                                {currentArticles.map((article) => (
                                    <Col key={article.article_id} xs={24} sm={12} md={8} lg={6} xl={6} className="card-item">
                                        <Link to={`/reading/article/${article.article_id}`} style={{ textDecoration: 'none' }}>
                                            <Card
                                                bordered={false}
                                                bodyStyle={{ padding: '24px', background: '#f7f7f7' }}
                                                hoverable
                                                className="small-card"
                                            >
                                                <Meta
                                                    title={<Text style={{ color: '#211f3f' }}>{article.title}</Text>}
                                                    description={article.content?.slice(0, 100) || '无内容'}
                                                />
                                            </Card>
                                        </Link>
                                    </Col>
                                ))}
                            </Row>
                            <Pagination
                                current={currentPage}
                                total={articles.length}
                                pageSize={articlesPerPage}
                                onChange={paginate}
                                showSizeChanger={false}
                                style={{ textAlign: 'center', marginTop: '20px' }}
                            />
                        </>
                    )}
                </div>
            </Content>
        </Layout>
    );
};

export default ArticleList;